package com.zhan.signalling.data.listener;

import java.util.Collection;
import java.util.Iterator;

import com.alibaba.fastjson.JSONObject;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.BroadcastOperations;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.listener.DataListener;
import com.zhan.signalling.check.AccoutPermissionCheck;
import com.zhan.signalling.commons.Constants;
import com.zhan.signalling.commons.SocketEvent;
import com.zhan.signalling.message.Message;
import com.zhan.signalling.message.Result;
import com.zhan.signalling.util.RedisUtil;

/**
 * 加入房间
 * @author knight
 *
 */
public class JoinGroupListener implements DataListener<Message> {

	public void onData(SocketIOClient client, Message data, AckRequest ackSender) throws Exception {
		
		// 校验权限
		AccoutPermissionCheck.check(client, SocketEvent.JOIN_GROUP_EVENT);
		
		String token = client.get(Constants.USER_TOKEN);
		String groupId = data.getGroupId();
		String platform = client.getNamespace().getName();
		//踢出用户不能再进入
		if(RedisUtil.isKickOut(platform +":"+ groupId, token)) {
			return;
		}
		// 重复用户再进入
		BroadcastOperations broadcastOperations = client.getNamespace().getRoomOperations(groupId);
		Collection<SocketIOClient> allClient = broadcastOperations.getClients();
		Iterator<SocketIOClient> ite = allClient.iterator();
		while(ite.hasNext()) {
			SocketIOClient cli = ite.next();
			if(cli.get(Constants.USER_TOKEN).equals(token)) {
				cli.leaveRoom(groupId);
				cli.disconnect();
			}
		}
		client.joinRoom(groupId);
		client.set(Constants.GROUP_KEY, groupId);
		JSONObject user = client.get(Constants.USER_KEY);
		client.getNamespace().getRoomOperations(groupId)
								.sendEvent(SocketEvent.JOIN_GROUP_EVENT, 
										new Result(user, Constants.SUCCESS));
		
	}

}
